<template>
	<div>
		<main-content
			:tableHeight.sync="tableHeight"
			:otherDependenComponents="otherDependenComponents"
		>
			<template slot="query">
				<el-form
					ref="formRef"
					:inline="true"
					:model="queryData"
					class="flex-warp-container"
				>
					<el-form-item class="flex-row-container" :label="$t('report.statistics_data')">
						<!-- <el-select
							v-model="dateFlag"
							style="width:140px"
							:placeholder="$t('common.please_choose')"
						>
							<el-option
								:label="$t('report.statistics_data')"
								value="1"
							/>
							<el-option
								:label="$t('report.real_time_data')"
								value="0"
							/>
						</el-select> -->
						<el-date-picker
							v-model="searchTime"
							size="medium"
							:picker-options="pickerShortcutWithCurrPeriod"
							type="daterange"
							range-separator="-"
							:start-placeholder="$t('report.start_date')"
							:end-placeholder="$t('report.end_date')"
							:clearable="false"
							:disabled="dateFlag == 0"
						></el-date-picker>
						<el-form-item class="margin-left-10" :label="$t('report.master_agent_account')" prop="topProxyName">
							<el-input
								v-model.trim="topProxyName"
								clearable
								:placeholder="$t('report.please_enter_agent_account')"
							></el-input>
						</el-form-item>
					</el-form-item>
					<el-form-item>
						<el-button
							type="primary"
							icon="el-icon-search"
							size="medium"
							:disabled="loading"
							@click="search"
						>
							{{ $t('common.search') }}
						</el-button>
						<el-button
							icon="el-icon-refresh-left"
							size="medium"
							:disabled="loading"
							@click="reset"
						>
							{{ $t('common.reset') }}
						</el-button>
						<el-button
							v-if="hasPermission('90930044')"
							type="warning"
							icon="el-icon-download"
							size="medium"
							:disabled="loading"
							:loading="exportLoading"
							@click="handleExportExcel"
						>
							{{ $t('common.export') }}
						</el-button>
					</el-form-item>
					<date-picker-shortcuts
						kind="shortcutForButtons"
						:action="handleShortcutBtnClick"
						:loading="loading"
					/>
				</el-form>
				<el-link :underline="false" type="danger">
					{{ $t('report.refresh_warning_text') }}
				</el-link>
			</template>
			<template slot="content">
				<el-table
					key="father"
					v-loading="loading"
					element-loading-spinner="el-icon-loading"
					border
					ref="elTable"
					size="mini"
					class="small-size-table"
					:data="tableData"
					style="width: 100%"
					show-summary
					@sort-change="changeTableSort"
					:max-height="tableHeight"
					highlight-current-row
					:summary-method="
						(val) => handleRow(val, totalSummary)
					"
					:header-cell-style="getRowClass"
				>
					<template v-for="(item, index) in newCol">
						<el-table-column
							:key="'column_' + index"
							:prop="item.prop"
							:align="item.alignCenter"
							:label="item.label"
							:min-width="item.minWidth"
							:fixed="item.isFixed"
							:show-overflow-tooltip="item.isShowTip"
							v-if="tableColumnData[item.label]"
						>
							<template
								slot="header"
								slot-scope="{ column, $index }"
							>
								<span
									@mousedown="
										handleMounseDown($event, column, $index)
									"
									@dragover="
										handleDragover($event, column, $index)
									"
								>
									{{ item.label }}
								</span>
							</template>
							<template slot-scope="{ row }">
								<div v-if="item.solt === 'numberSolt'">
									{{ handleNumber('', row[item.prop], 0) }}
								</div>
								<div v-if="item.solt === 'amountSolt'">
									<p>
										{{
											handleTotalNumber(
												row.currency,
												row[item.prop]
											)
										}}
									</p>
								</div>
								<div v-if="item.solt === 'defaultSolt'">
									<span>
										{{ row[item.prop] || '-' }}
									</span>
								</div>
								<div v-if="item.solt === 'percentage'">
									<span>
										{{ (row[item.prop] || 0) + '%' }}
									</span>
								</div>
								<div v-if="item.solt === 'profit'">
									<span
										:style="
											handleNumberColor(row[item.prop])
										"
									>
										{{ handleCurrency('$') }}
										{{ handleNumber('$', row[item.prop]) }}
									</span>
								</div>
							</template>
						</el-table-column>
					</template>
				</el-table>

				<el-pagination
					v-show="!!total"
					class="pageValue"
					:current-page.sync="pageNum"
					background
					layout="total, sizes,prev, pager, next, jumper"
					:page-size.sync="pageSize"
					:page-sizes="pageSizes"
					:total="total"
					:pager-count="9"
					@current-change="handleCurrentChange"
					@size-change="handleSizeChange"
				></el-pagination>
			</template>
		</main-content>
	</div>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import { routerNames } from '@/utils/consts'
import summaryList from './components/summaryList'
import MainContent from '@/components/MainContent/index.vue'
import DatePickerShortcuts from '@/components/DatePickerShortcuts'
import { getColumns } from './components/columns'

const setSearchTime = () => [
	dayjs()
		.subtract(6, 'day')
		.startOf('day'),
	dayjs()
		.subtract(0, 'day')
		.endOf('day')
]
export default {
	name: routerNames.masterAgentReport,
	components: {
		DatePickerShortcuts,
		MainContent
	},
	mixins: [list, summaryList],
	data() {
		return {
			tableHeight: 480,
			otherDependenComponents: [],
			exportLoading: false,
			queryData: {},
			newCol: '',
			searchTime: setSearchTime(),
			tableData: [],
			totalSummary: {},
			dateFlag: '1',
			merchantObj: '',
			axiosDate: '',
			colSettings: {
				visible: false,
				dialogColumnData: {}
			},
			activityListField: {},
			page: 1,
			size: 100,
			totalRecord: 0,
			topProxyName: ''
		}
	},
	created() {
		this.newCol = getColumns()
		for (const index in this.newCol) {
			this.activityListField[this.newCol[index].label] = true
		}
		this.initIndexDB('statusOverviewTripartite', this.activityListField)
	},
	methods: {
		initList: () => {}, // 本页需求是不自动加载数据，所以用此空方法覆盖mixing里面的initList
		handleShortcutBtnClick(val) {
			this.searchTime = val
			this.search()
		},
		changeTableSort({ column, prop, order }) {
			this.queryData.orderKey = prop
			if (order === 'ascending') {
				this.queryData.orderType = 'asc'
			} else if (column.order === 'descending') {
				this.queryData.orderType = 'desc'
			} else {
				delete this.queryData.orderKey
				delete this.queryData.orderType
			}
			this.loadData()
		},
		loadData() {
			if (+new Date() - 500 < this.axiosDate) return
			const timeArr = this.searchTime || []
			let params = {
				...this.queryData,
				dataAreaType: Number(this.dateFlag),
				startDate:
					this.dateFlag === '1'
						? dayjs(timeArr[0]).format('YYYYMMDD')
						: undefined,
				endDate:
					this.dateFlag === '1'
						? dayjs(timeArr[1]).format('YYYYMMDD')
						: undefined,
				topProxyName: this.topProxyName || undefined
			}
			params = this.getParams(params)

			this.tableData = []
			const minM = dayjs(timeArr[0])
			const maxM = dayjs(timeArr[1])
			const month = dayjs(maxM).diff(minM, 'month')

			if (month >= 12) {
				this.$message.warning(this.$t('report.12_month'))
				this.total = 0
				return
			}
			this.loading = true
			this.pageCurrency = this.merchantObj?.currency || ''

			this.$api
				.masterAgentReportList(params)
				.then((res) => {
					this.loading = false
					this.axiosDate = +new Date()
					this.tableData = res?.data?.record || []
					this.total = res?.data?.totalRecord || 0
				})
				.catch(() => {
					this.loading = false
				})

			this.$api
				.masterAgentReportSummary(params)
				.then((res) => {
					this.loading = false
					this.totalSummary = res?.data || {}
				})
				.catch(() => {
					this.loading = false
				})
		},
		clear() {
			this.$refs.formSub.resetFields()
		},
		search() {
			this.pageNum = 1
			this.loadData()
		},
		reset() {
			this.pageNum = 1
			this.queryData = {}
			this.merchantObj = ''
			this.dateFlag = '1'
			this.searchTime = setSearchTime()
			if (this.$refs.elTable) {
				this.$refs.elTable.clearSort()
			}
			this.topProxyName = ''
			this.loadData()
		},
		handleExportExcel() {
			const timeArr = this.searchTime || []
			const params = {
				...this.queryData,
				dataAreaType: Number(this.dateFlag),
				startDate: dayjs(timeArr[0])
					.startOf('day')
					.format('YYYYMMDD'),
				endDate: dayjs(timeArr[1])
					.endOf('day')
					.format('YYYYMMDD'),
				topProxyName: this.topProxyName || undefined
			}
			this.exportLoading = true
			this.exportExcelPublic({
				api: 'masterAgentReportSummaryExport',
				params
			}).finally(() => {
				this.exportLoading = false
			})
		},
		handleCurrentChange(value) {
			this.pageNum = value
			this.loadData()
		}
	}
}
</script>

<style lang="scss" scoped>
.tips-box {
	position: absolute;
	right: 10px;
	top: 50%;
	margin-top: -12px;
}
::v-deep .el-dialog__header {
	color: #909399;
	font-weight: 700;
}
::v-deep .el-table__fixed-footer-wrapper .cell,
::v-deep .el-table__footer-wrapper .cell {
	height: 100%;
	padding: 0 !important;
	margin: 0 !important;
	> div {
		height: 100%;
	}
}
::v-deep .footer_count_row {
	min-height: 50px;
	height: 50%;
	display: flex;
	font-weight: 700;
	padding: 5px 0;
	align-items: center;
	flex-direction: column;
	justify-content: center;
}
::v-deep .footer_count_row_border {
	border-top: 1px solid #ebeef5;
}
::v-deep .is-group th {
	background-color: #f5f7fa !important;
}
::v-deep .maincontent .params {
	display: none;
}
.content-top {
	display: flex;
	align-items: center;
	justify-content: flex-end;
	margin-bottom: 10px;
}
::v-deep .rempadding .el-dialog__body {
	padding: 0;
	padding-bottom: 20px;
	.contentBox {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.contentBox,
	form {
		padding: 0 20px;
	}
}
.margin-left-10 {
	margin-left: 10px;
}
</style>